<script setup lang="ts">
import { onMounted, onBeforeUnmount, watch, ref, reactive } from 'vue'
import * as echarts from 'echarts'
import { CaretRight } from '@element-plus/icons-vue'
import { headersStore } from '@/stores/apiHeader'
import { DEFAULT_ECHARTS_FONTSIZE,DIALOG_ECHARTS_FONTSIZE } from '@/Utils/setting'
import { useDialogStore } from '@/stores/dialog'
const dialogStore = useDialogStore()
const { dialogInfo } = dialogStore

const fontSize = dialogInfo.visible ? DIALOG_ECHARTS_FONTSIZE : DEFAULT_ECHARTS_FONTSIZE
const dialogInfoVisible = dialogInfo.visible

const props = defineProps<{
  chartData: any
}>()
props.chartData.name = props.chartData.name + Math.random()

watch(
  () => props.chartData,
  () => {
    createChart()
  },
  { deep: true }
)

// 调整px到合适的大小
const changePixelSize = (px: number) => {
  // 获取当前屏幕宽度
  const width = document.body.clientWidth
  let res = (px / 1920) * width
  // 保留整数
  return parseInt(res.toFixed(0))
}

// 返回值是千分位逗号隔开的字符串
const numberFormat = (num: number) => {
  if (num == undefined) {
    return ''
  }
  return num.toString().replace(/\d+/, function (n) {
    // 先提取整数部分
    return n.replace(/(\d)(?=(\d{3})+$)/g, function ($1) {
      return $1 + ','
    })
  })
}

const paginate = reactive({
  currentPage: 1,
  pageSize: 0,
  total: 0,
  totalPage: 0,
})

// 向右箭头翻页
const nextPage = () => {
  // 如果paginate.currentPage小于paginate.totalPage 加1
  if (paginate.currentPage < paginate.totalPage) {
    paginate.currentPage += 1
  } else {
    paginate.currentPage = 1
  }
  createChart()
}

let myChart: any
const createChart = () => {
  // info需要2个值
  const info = props.chartData.data || []

  console.log('info', info)
  if(info.length !=2 ){
    return ''
  }


  myChart = echarts.getInstanceByDom(
    document.getElementById(props.chartData.name)
  )
  //如果为空 则正常进行渲染 反之 不再进行初始化
  if (myChart == null) {
    myChart = echarts.init(document.getElementById(props.chartData.name))
  }
  myChart.dispatchAction({
    type: 'hideTip',
  })
  paginate.total = props.chartData.sub_titles.length
  paginate.pageSize = props.chartData.paginate.pageSize || 99
  paginate.totalPage = Math.ceil(paginate.total / paginate.pageSize)
  const start = (paginate.currentPage - 1) * paginate.pageSize
  const end = paginate.currentPage * paginate.pageSize

  // 获取到两大名称
  const title1 = info[0].name
  const title2 = info[1].name
  const data1 = info[0].data.slice(start, end)
  const data2 = info[1].data.slice(start, end)
  const xTitleArr = props.chartData.sub_titles.slice(start, end)

  // 库存折线
  const lineSeries = {
    name: title1,
    type: 'line',
    yAxisIndex: 0,
    data: data1,
    itemStyle: {
        color: props.chartData.color[1]
    },
  }
  // 出库柱
  const barSeries = {
    name: title2,
    type: 'bar',
    barWidth: changePixelSize(20),
    yAxisIndex: 1,
    data: data2,
    itemStyle: {
        color: props.chartData.color[0],
        opacity: 0.8,
    },
    emphasis: {
      focus: 'none',
      itemStyle: {
        opacity: 1,
      },
    },
  }

  const minNum1 = Math.min(...info[0].data)// 库存量最小值
  const maxNum1 = Math.max(...info[0].data)// 库存量最大值
  const minNum2 = Math.min(...info[1].data)// 出库量最小值
  const maxNum2 = Math.max(...info[1].data)// 出库量最大值
  const min1 = maxNum1-minNum1 > 0 ? minNum1 -(maxNum1-minNum1)/8 : 0
  const max1 = maxNum1-minNum1 > 0 ? maxNum1 +(maxNum1-minNum1)/8 : 0
  const min2 = maxNum2-minNum2 > 0 ? minNum2 -(maxNum2-minNum2)/8 : 0
  const max2 = maxNum2-minNum2 > 0 ? maxNum2 +(maxNum2-minNum2)/8 : 0

  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'none'
      },
      textStyle: {
        fontSize: changePixelSize(fontSize),
        color: '#fff', //设置文字颜色
      },
      confine: true,
      backgroundColor: 'rgba(0,0,0,0.7)', //默认值，提示背景颜色，默认为透明度为0.7的黑色
    },
    grid: {
      left: '1%',
      bottom: '6%',
      top: '26%',
      containLabel: true,
    },
    legend: {
      textStyle: {
        color: '#fff',
        fontSize: changePixelSize(fontSize),
      },
      // 右上角
      top: changePixelSize(1),
      right: changePixelSize(2),
    },
    xAxis: {
      name: props.chartData.xAxisName || '',
      nameTextStyle: {
        color: '#fff',
        fontSize: changePixelSize(fontSize),
      },
      type: 'category',
      data: xTitleArr,
      axisLine: { show: false },
      axisTick: { show: false },
      splitLine: { show: false },
      axisLabel: {
        color: '#fff', // 设置 X 轴标签字体颜色
        fontSize: changePixelSize(fontSize),
        interval: 0, // 强制显示所有标签
        offset: 1,
        align: 'center',
        formatter:dialogInfoVisible==false? function (str: any) {
          // 中文算2,英文算1,数到maxLength截取,然后打...
          let count = 0
          let result = ''
          const maxLength = props.chartData.titleRotate ? 14 : 8

          for (let i = 0; i < str.length; i++) {
            const char = str.charAt(i)
            count += /[\u4E00-\u9FA5]/g.test(char) ? 2 : 1

            if (count > maxLength) {
              result += '...'
              break
            }

            result += char
          }
          return result
        }: function (str: any) {
          // 中文算2,英文算1,数到maxLength截取,然后打...
          let count = 0
          let result = ''
          const maxLength = props.chartData.titleRotate ? 14 : 10

          for (let i = 0; i < str.length; i++) {
            const char = str.charAt(i)
            count += /[\u4E00-\u9FA5]/g.test(char) ? 2 : 1

            if (count > maxLength) {
              result += '...'
              break
            }

            result += char
          }
          return result
        },
      },
    },
    yAxis: [
      {
        type: 'value',
        name: title1,
        min: min1,
        max: max1,
        interval: (max1 - min1) / 4,
        axisLabel: {
          fontSize: changePixelSize(fontSize),
          color: '#FFFFFF',
          formatter: function (params) {
            return numberFormat(params.toFixed(0));
          }
        },
        axisTick: {
          show: false
        },
        axisLine: { show: true, lineStyle: { color: '#fff' } },
        splitLine: {
          show: true,
          lineStyle: {
            color: '#2b3f7c',
            type: [5, 10],
          },
        },
        nameTextStyle: {
          color: '#fff',
          fontSize: changePixelSize(fontSize),
        },
      },
      {
        type: 'value',
        name: title2,
        min: min2,
        max: max2,
        interval: (max2 - min2) / 4,
        axisLabel: {
          fontSize: changePixelSize(fontSize),
          color: '#FFFFFF',
          formatter: function (params) {
            return numberFormat(params.toFixed(0));
          }
        },
        axisTick: {
          show: false
        },
        axisLine: { show: true, lineStyle: { color: '#fff' } },
        splitLine: {
          show: true,
          lineStyle: {
            color: '#2b3f7c',
            type: [5, 10],
          },
        },
        nameTextStyle: {
          color: '#fff',
          fontSize: changePixelSize(fontSize),
        },
      },
    ],
    series: [lineSeries, barSeries],
  }
  // 绘制图表
  myChart.setOption(option)
}
onMounted(() => {
  setTimeout(() => {
    createChart()
  }, 300)
})

onBeforeUnmount(() => {
  if (myChart) {
    myChart.dispose()
  }
})
</script>

<template>
  <div
    :class="{
      'echart-box': true,
      'bottom-box': chartData.position == 'bottom',
      'dialog-box': dialogInfoVisible == true,
    }"
  >
    <el-button
      class="next-button"
      type="primary"
      :icon="CaretRight"
      @click="nextPage"
      v-if="props.chartData.paginate && paginate.totalPage > 1"
    />
    <div class="chart" :id="chartData.name"></div>
  </div>
</template>
<style lang="scss" scoped>
.echart-box {
  position: relative;
  width: 100%;
  height: calc(
    260px - 45px
  ); // 45px 是标题 35 高度+10px 轮播图指示器预留空间高度
  .chart {
    width: 100%;
    height: 100%;
  }
  .test-btn {
    position: absolute;
    bottom: 0;
    right: 0;
  }
}
.bottom-box {
  height: calc(
    210px - 45px
  ); // 45px 是标题 35 高度+10px 轮播图指示器预留空间高度
}
.dialog-box {
  height: calc(
    500px - 45px
  ); // 45px 是标题 35 高度+10px 轮播图指示器预留空间高度
}
.next-button {
  width: 20px;
  height: 20px;
  position: absolute;
  opacity: 0.9;
  right: 2%;
  top: 50%;
  transform: translateY(-50%);
  z-index: 999;
  background-color: #556fb5;
  color: #00eef0;
  border: 0;
}
</style>
